<template>
    <div class="app-container">
        <el-row>
            <el-col :span="18">
                <!-- 帮助状态 -->
                <el-row :gutter="24" style="color: #9bb1e9;" class="mb15">
                    <el-col :span="1.5">
                        状态
                    </el-col>
                    <el-col :span="1.5" :class="isActive('all')" @click="changeStatus('all')">
                        全部
                    </el-col>
                    <el-col :span="1.5" :class="isActive('emit')" @click="changeStatus('emit')">
                        发出
                    </el-col>
                    <el-col :span="1.5" :class="isActive('draft')" @click="changeStatus('draft')">
                        草稿
                    </el-col>
                    <el-col :span="1.5" :class="isActive('complete')" @click="changeStatus('complete')">
                        完成
                    </el-col>
                    <el-col :span="1.5" :class="isActive('expire')" @click="changeStatus('expire')">
                        过期
                    </el-col>
                    <el-col :span="1.5" :class="isActive('cancel')" @click="changeStatus('cancel')">
                        取消
                    </el-col>
                </el-row>
            </el-col>
            <el-col :span="6">
                <!-- 头部操作按钮 -->
                <el-row :gutter="10" class="mb15">
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
            </el-col>
        </el-row>
        <!-- 搜索栏 -->
        <el-form :model="queryParams" :inline="true" v-show="showSearch">
            <el-form-item label="主题">
                <el-input @keyup.enter="handleQuery" v-model="queryParams.keyword" style="width: 150px"
                          placeholder="请输入帮助主题" clearable/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            </el-form-item>
        </el-form>
        <!-- 表格展示 -->
        <el-table :data="helpList" v-loading="loading"
                  border height="500" :default-sort="{ prop: 'createTime', order: 'descending' }">
            <!-- 表格列 -->
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <!--缩略图-->
            <el-table-column prop="cover" label="缩略图" width="200" align="center">
                <template #default="scope">
                    <el-image class="help-cover" :src="scope.row.cover"></el-image>
                    <el-icon v-if="scope.row.status == 1" class="help-status-icon">
                        <View/>
                    </el-icon>
                    <el-icon v-if="scope.row.status == 2" class="help-status-icon">
                        <Hide/>
                    </el-icon>
                    <el-icon v-if="scope.row.status == 3" class="help-status-icon">
                        <EditPen/>
                    </el-icon>
                </template>
            </el-table-column>
            <!-- 帮助标题 -->
            <el-table-column prop="title" label="主题" align="center"></el-table-column>
            <!-- 需要人数 -->
            <el-table-column prop="peopleNumber" width="100" label="需要人数" align="center"></el-table-column>
            <!-- 帮助浏览量 -->
            <el-table-column prop="viewCount" label="浏览量" width="100" align="center" sortable></el-table-column>
            <!-- 发表人 -->
            <el-table-column prop="nickname" label="发表人昵称" align="center" width="100"></el-table-column>
            <template v-if="activeStatus === 'complete'">
                <!-- 应约者 -->
                <el-table-column prop="destinedUserId" label="应约者ID"
                                 align="center" width="100"></el-table-column>
            </template>
            <!-- 开始时间 -->
            <el-table-column prop="timeStart" width="200" label="开始时间" align="center" sortable>
                <template #default="scope">
                    <div class="create-time">
                        <el-icon>
                            <clock/>
                        </el-icon>
                        <span style="margin-left: 10px">{{ formatDateTime(scope.row.timeStart) }}</span>
                    </div>
                </template>
            </el-table-column>
            <!-- 结束时间 -->
            <el-table-column prop="timeEnd" width="200" label="结束时间" align="center" sortable>
                <template #default="scope">
                    <div class="create-time">
                        <el-icon>
                            <clock/>
                        </el-icon>
                        <span style="margin-left: 10px">{{ formatDateTime(scope.row.timeEnd) }}</span>
                    </div>
                </template>
            </el-table-column>
            <!-- 操作 -->
            <el-table-column width="80" label="操作" align="center" fixed="right">
                <template #default="scope">
                    <el-button type="primary" icon="Edit" link @click="handleEdit(scope.row.id)"
                               v-if="scope.row.status == 1 || scope.row.status == 2">
                        编辑
                    </el-button>
                    <el-button style="margin-left: 0" type="danger" icon="Delete" link
                               @click="handleDelete(scope.row.id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination v-if="count > 0" :total="count" v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize" @pagination="getList"/>
        <!-- 修改对话框 -->
        <el-dialog title="修改帮助" v-model="addOrUpdate" width="60%" top="0.5vh" @close="cancel"
                   append-to-body center>
            <el-form ref="helpFormRef" label-width="80px" :model="helpForm" :rules="rules">
                <!-- 帮助主题 -->
                <el-form-item label="帮助主题" prop="title">
                    <el-input placeholder="请输入主题" v-model="helpForm.title" style="width: 100%;"/>
                </el-form-item>
                <!-- 时间范围 -->
                <el-form-item label="时间范围" prop="timeStart">
                    <el-date-picker
                            v-model="timeRange"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                    />
                </el-form-item>
                <!-- 帮助内容 -->
                <el-form-item label="帮助内容" prop="content">
                    <md-editor ref="editorRef" v-model="helpForm.content"
                               class="md-container" :toolbars="toolbars1" @on-upload-img="uploadImg"
                               placeholder="请输入帮助内容...">
                        <template #defToolbars>
                            <emoji-extension :on-insert="insert"/>
                        </template>
                    </md-editor>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="success" @click="submitForm">保存帮助</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {computed, onMounted, reactive, ref, toRefs} from "vue";
import {Agreement, AgreementForm, AgreementQuery, SaveCondition, UserIntro} from "@/api/agreement/types";
import {deleteAgreement, editAgreement, getAgreementList, updateAgreement, uploadAgreementImage} from "@/api/agreement";
import {formatDateTime} from "@/utils/date";
import {messageConfirm, notifySuccess} from "@/utils/modal";
import {FormInstance, FormRules} from "element-plus";
import {AxiosError} from "axios";
import EmojiExtension from '@/components/EmojiExtension/index.vue';
import MdEditor, {InsertContentGenerator} from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import {toolbars1} from "@/components/EmojiExtension/staticConfig";

const editorRef = ref();
const helpFormRef = ref<FormInstance>();
const isActive = computed(() => {
    return function (value: string | undefined) {
        return activeStatus.value == value ? "active-status" : "status";
    }
});
const rules = reactive<FormRules>({
    title: [{required: true, message: "帮助主题不能为空", trigger: "blur"}],
    content: [{required: true, message: "帮助内容不能为空", trigger: "blur"}],
    timeStart: [{required: true, message: "时间范围不能为空", trigger: "blur"}],
});
const data = reactive({
    timeRange: [] as string[],
    addOrUpdate: false,
    count: 0,
    showSearch: true,
    loading: false,
    queryParams: {
        type: 4, // 帮助
        pageNum: 1,
        pageSize: 10,
    } as AgreementQuery,
    saveCondition: {
        id: 0,
        agreementType: 4
    } as SaveCondition,
    helpList: [] as Agreement[],
    helpForm: {
        id: undefined,
        userId: 1,
        title: "",
        content: "",
        status: 2,
        timeStart: "",
        timeEnd: "",
        userIntroList: [] as UserIntro[],
        type: undefined,
        agreementType: 4,
    } as AgreementForm,
    activeStatus: "all",
})

const {
    addOrUpdate, count, showSearch, loading,
    queryParams, helpList, timeRange,
    activeStatus, saveCondition, helpForm
} = toRefs(data)

const changeStatus = (status: string) => {
    switch (status) {
        case "all":
            queryParams.value.status = undefined;
            break;
        case "emit":
            queryParams.value.status = 1;
            break;
        case "draft":
            queryParams.value.status = 2;
            break;
        case "complete":
            queryParams.value.status = 3;
            break;
        case "expire":
            queryParams.value.status = 4;
            break;
        case "cancel":
            queryParams.value.status = 5;
            break;
    }
    activeStatus.value = status;
    handleQuery();
};
const insert = (generator: InsertContentGenerator) => {
    editorRef.value?.insert(generator);
};
const uploadImg = async (files: Array<File>, callback: (urls: string[]) => void) => {
    const res = await Promise.all(
        files.map((file) => {
            return new Promise((rev, rej) => {
                const form = new FormData();
                form.append('file', file);
                uploadAgreementImage(form).then(({data}) => {
                    if (data.flag) {
                        rev(data);
                    }
                }).catch((error: AxiosError) => rej(error));
            });
        })
    );
    callback(res.map((item: any) => item.data));
};
const cancel = () => {
    addOrUpdate.value = false;
    helpFormRef.value?.clearValidate();
    reset();
};
const reset = () => {
    helpForm.value = {
        id: undefined,
        userId: 1,
        title: "",
        content: "",
        status: 2,
        timeStart: "",
        timeEnd: "",
        userIntroList: [] as UserIntro[],
        type: undefined,
        agreementType: 4,
    };
};
const handleEdit = (id: number) => {
    saveCondition.value.id = id;
    editAgreement(saveCondition.value).then(({data}) => {
        if (data.flag) {
            helpForm.value = data.data;
            helpForm.value.agreementType = 4;
            timeRange.value = [data.data.timeStart, data.data.timeEnd];
            addOrUpdate.value = true;
        }
    })
};
const handleDelete = (id: number) => {
    messageConfirm("确认删除该帮助?").then(() => {
        saveCondition.value.id = id;
        deleteAgreement(saveCondition.value).then(({data}) => {
            if (data.flag) {
                notifySuccess(data.msg);
                getList();
            }
        });
    }).catch(() => {
    });
};
const submitForm = () => {
    // 设置时间范围
    helpForm.value.timeStart = timeRange.value[0];
    helpForm.value.timeEnd = timeRange.value[1];
    helpFormRef.value?.validate((valid) => {
        if (valid) {
            updateAgreement(helpForm.value).then(({data}) => {
                if (data.flag) {
                    notifySuccess(data.msg);
                    getList();
                }
                cancel();
            }).catch(() => {
            });
        }
    })
};
const getList = () => {
    loading.value = true;
    getAgreementList(queryParams.value).then(({data}) => {
        helpList.value = data.rows;
        count.value = data.total;
        loading.value = false;
    })
};
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};
onMounted(() => {
    getList();
});
</script>

<style scoped>
.md-container {
    min-height: 300px;
    height: calc(100vh - 300px);
}

.status {
    cursor: pointer;
}

.active-status {
    cursor: pointer;
    color: rgba(80, 166, 31, 0.8);
    font-weight: bold;
}

.help-cover {
    position: relative;
    width: 100%;
    height: 80px;
    border-radius: 5px;
}

.help-cover::after {
    content: "";
    background: rgba(0, 0, 0, 0.3);
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

.help-status-icon {
    color: #e8eaf1;
    font-size: 1rem;
    position: absolute;
    right: 1rem;
    bottom: 1rem;
}
</style>